package com.example.util;

import cn.hutool.setting.dialect.Props;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.io.IOUtils;

import java.io.*;


/**
 *  上传图片到服务器工具类
 *
 **/
public class QiniuUpload {
    static Props props = new Props("qiuniu.properties");
    //设置好账号的ACCESS_KEY和SECRET_KEY
    private static String ACCESS_KEY; //这两个登录七牛 账号里面可以找到
    private static String SECRET_KEY;
    //储存空间名（注意设置公开）
    private static String BUCKET;
    //七牛默认域名
    private static String DOMAIN;
    static {

        ACCESS_KEY = props.getProperty("accessKey");
        SECRET_KEY = props.getProperty("secretKey");
        BUCKET = props.getProperty("bucket");
        DOMAIN = props.getProperty("domain");
    }


    //密钥配置
    private static Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    private static Configuration cfg = new Configuration(Zone.huanan());

    //创建上传对象
    private static UploadManager uploadManager = new UploadManager(cfg);

    //简单上传，使用默认策略，只需要设置上传的空间名就可以了
    public static String getUpToken(){
        return auth.uploadToken(BUCKET);
    }

    /**
     * 视频上传至七牛
     */
    public static String uploadByFile(InputStream is,String filename) {
        // 1、构造一个带指定 Region 对象的配置类。指定存储区域，和存储空间选择的区域一致
        Configuration cfg = new Configuration(Zone.zone2());
        // ...其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);
        // 2、认证
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        // 认证通过后得到 token（令牌）认证凭证
        String upToken = auth.uploadToken(BUCKET);

        //返回文件访问的url
        String fileUrl = null;

        try {
            byte[] uploadBytes = IOUtils.toByteArray(is);
            ByteArrayInputStream uploadInputStream = new ByteArrayInputStream(uploadBytes);
            String key = filename;
            Response response = uploadManager.put(uploadInputStream, key, upToken, null, null);
            // 4、解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println("文件名：" + putRet.key);
            System.out.println("文件内容的hash值：" + putRet.hash);
            fileUrl = DOMAIN+"/"+filename;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                // ignore
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileUrl;
    }
}